package cn.tom.controller;

import cn.hutool.json.JSONUtil;
import cn.tom.entity.*;
import cn.tom.exceptiom.TomException;
import cn.tom.service.BookService;
import cn.tom.service.CartService;
import cn.tom.service.OrderService;
import cn.tom.tool.RedisCache;
import cn.tom.tool.Token;
import cn.tom.tool.XJson;
import cn.tom.tool.XResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping({"/api/fore/cart"})
public class CartController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    CartService cartService;
    @Autowired
    OrderService orderService;

    @Autowired
    RedisCache redisCache;

    @GetMapping({"/findMyCarts"})
    public XJson findMyCarts() {
        int uid =Token.getUid();
        log.info("uid=========="+ uid);
        return XResp.pack(200,"", cartService.findByUid(uid));
    }


    @PostMapping({"/uniadd2Order"})
    public XJson uniadd2Order(@RequestBody UniCart2Ord uniCart2Ord) {
        Map<String, Object> map = new HashMap<>();
        int uid = Token.getUid();
        if (uid < 0) {
            return XResp.pack(401, "未登录或登录超时", null);
        }
        uniCart2Ord.setUid(uid);
        this.log.info("开始创建订单:" + uniCart2Ord.toString());
        List<Cart> list = JSONUtil.toList(uniCart2Ord.getCarts(), Cart.class);
        System.out.println("uniapp cart======="+ list.toString());
        try {
            Map<String, Book> books = redisCache.getCacheMap("books");
            List<Cart> carts = list;
            for (Cart cart : carts) {
                Integer id = cart.getBook().getId();
                Integer num = cart.getNum();
                Book book = books.get(String.valueOf(id));
                if (book.getStock()<num) {
                    return XResp.pack(210, book.getName()+"库存不足", null);
                }
            }
            this.orderService.uniaddCart2Ord(uniCart2Ord);
            map.put("ordid", uniCart2Ord.getOrdid());
            map.put("amount", uniCart2Ord.getAmount());
            return XResp.pack(200, "成功接收到数据, 并产生订单 ....", map);
        } catch (Exception e) {
            return XResp.pack(500, "成功接收到数据, 但更新订单失败 ....", null);
        }
    }

    @PostMapping({"/add2Order"})
    public XJson add2Order(@RequestBody Cart2Ord cart2Ord) {
        Map<String, Object> map = new HashMap<>();
        int uid = Token.getUid();
        if (uid < 0) {
            return XResp.pack(401, "未登录或登录超时", null);
        }
        cart2Ord.setUid(uid);
        this.log.info("开始创建订单:" + cart2Ord.toString());
        try {
            Map<String, Book> books = redisCache.getCacheMap("books");
            List<Cart> carts = cart2Ord.getCarts();
            for (Cart cart : carts) {
                Integer id = cart.getBook().getId();
                Integer num = cart.getNum();
                Book book = books.get(String.valueOf(id));
                if (book.getStock()<num) {
                    return XResp.pack(210, book.getName()+"库存不足", null);
                }
            }
            this.orderService.addCart2Ord(cart2Ord);
            map.put("ordid", cart2Ord.getOrdid());
            map.put("amount", cart2Ord.getAmount());
            return XResp.pack(200, "成功接收到数据, 并产生订单 ....", map);
        } catch (Exception e) {
            return XResp.pack(500, "成功接收到数据, 但更新订单失败 ....", null);
        }
    }

    @GetMapping({"/remove/{id}"})
    public XJson remove(@PathVariable("id") int id) {
        int uid =Token.getUid();
        log.info("=============cart remove uid=========="+ uid);
        Integer ret = cartService.remove(id);
        if (ret>0) {
            return XResp.pack(200,"删除成功", ret);
        }
        return XResp.pack(201,"删除失败", ret);
    }
}
